const { Op } = require("sequelize");
const User = require("../../model/User");
const crypto = require("crypto");
// 添加用户
exports.addUser = async function (userObj) {
	const ins = await User.create({
		id: crypto.randomUUID(),
		name: "名字",
		phone: "13145214954",
		loginName: "admin",
		loginPwd: "admin",
	});
	console.log(ins.toJSON(), "添加成功");
	return ins.toJSON();
};
// 删除用户
exports.deleteUser = async function (id) {
	const res = await User.destroy({
		where: {
			id: id,
		},
	});
	if(!res) {
		throw "用户不存在";
	}
};
// 修改用户
exports.updateUser = async function (id, userObj) {
	const res = await User.update(
		{
			name: userObj.name,
			phone: userObj.phone,
			loginName: userObj.loginName,
			loginPwd: userObj.loginPwd,
		},
		{
			where: {
				id: id,
			},
		}
	);
	if(!res[0]) {
		throw "用户不存在";
	}
};
// 修改状态
exports.updateUserState = async function (id, userState) {
	await User.update(
		{
			userState: userState,
		},
		{
			where: {
				id: id,
			},
		}
	);
};
// 查询用户列表
exports.getUser = async function (page = 1, limit = 10, keyword = "", status = 0) {
	// const res = await User.findAll({
	//   offset: (page - 1) * limit,
	//   limit: limit,
	// })
	// const total = User.count()
	// return {
	//   total,
	//   data: JSON.parse(JSON.stringify(res))
	// }
	const where = {};
	if (keyword) {
		where.name = {
			[Op.like]: `%${keyword}%`,
		};
	}
	if (status > 0) {
		where.userState = status;
	}
	const res = await User.findAndCountAll({
		where,
		offset: (page - 1) * limit,
		limit: +limit,
		attributes: [
			"id",
			"name",
			"phone",
			"loginName",
			"userState",
			"createdAt"
		], // 查询需要的数据
	});
	return {
		total: res.count,
		data: JSON.parse(JSON.stringify(res.rows)),
	};
};
// 查询用户信息
exports.getUserInfo = async function (id) {
	const res = await User.findByPk(id, {
		attributes: [
			"id",
			"name",
			"phone",
			"loginName",
			"userState",
			"totalIncome",
			"totalSpent",
			"createdAt"
		], // 查询需要的数据
	});
	if (!res) {
		throw "用户不存在";
	}
	return res.toJSON();
};
